package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.item.entity.*;
import com.leyou.item.mapper.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service

public class GoodsService  {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SpuDetailMapper spuDetailMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;


    //查询
    public PageInfo<TbSpuBo> querySpuBosByKey(String key,Integer page,Integer rows,Boolean saleable){
        if(rows>0)PageHelper.startPage(page,Math.min(rows,100));
        Example example = new Example(TbSpu.class);
        Example.Criteria criteria = example.createCriteria();

        if(saleable!=null) criteria.andEqualTo("saleable",saleable);

        if(StringUtils.isNotBlank(key))criteria.andLike("title","%"+key+"%");
        criteria.andEqualTo("valid",true);

        List<TbSpu> tbSpus = spuMapper.selectByExample(example);
        List<TbSpuBo> collect = tbSpus.stream().map(spu -> {
            TbSpuBo tbSpuBo = new TbSpuBo();
            BeanUtils.copyProperties(spu, tbSpuBo);
            List<String> strings = categoryService.queryCategoryNamesByCids(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()));
            tbSpuBo.setCname(StringUtils.join(strings, "/"));
            tbSpuBo.setBname(brandMapper.selectByPrimaryKey(spu.getBrandId()).getName());
            return tbSpuBo;
        }).collect(Collectors.toList());

        return new PageInfo<>(collect);

    }

    //添加商品
    @Transactional
    public void addGoods(TbSpuBo spuBo){
        spuBo.setId(null);
        spuBo.setValid(true);//有效
        spuBo.setSaleable(true);//上架
        spuBo.setCreateTime(new Date());//创建时间
        spuBo.setLastUpdateTime(spuBo.getCreateTime());//最后修改时间
        spuMapper.insertSelective(spuBo);//添加spu

        spuBo.getSpuDetail().setSpuId(spuBo.getId());//关联spu详情数据
        spuDetailMapper.insertSelective(spuBo.getSpuDetail());//添加spu详情

        for (TbSku skus : spuBo.getSkus()) {//循环遍历sku
            if(!skus.getEnable()){//判断是否有效
                continue;//无效结束本次循环，继续下次循环
            }
            skus.setId(null);
            skus.setSpuId(spuBo.getId());//关联spu属性
            skus.setCreateTime(new Date());//创建时间
            skus.setLastUpdateTime(skus.getCreateTime());//最后修改时间
            skuMapper.insertSelective(skus);//添加sku
            TbStock tbStock = new TbStock();//创建sku写的对象
            tbStock.setSkuId(skus.getId());//关联sku
            tbStock.setStock(skus.getStock());//存储sku数量

            stockMapper.insertSelective(tbStock);//添加sku数量数据
        }
        //发送添加的消息
        sendMessage("insert",spuBo.getId());

    }

    //使用rabbitMQ发送消息
    public void sendMessage(String type,Long id) {
        try {
            amqpTemplate.convertAndSend("item."+type,id);
        } catch (AmqpException e) {
            e.printStackTrace();
        }
    }

    //修改商品
    @Transactional
    public void updateGoods(TbSpuBo spuBo){
        spuBo.setLastUpdateTime(new Date());//最后修改时间
        spuMapper.updateByPrimaryKeySelective(spuBo);//修改spu
        spuBo.getSpuDetail().setSpuId(spuBo.getId());//关联spu详情数据
        spuDetailMapper.updateByPrimaryKeySelective(spuBo.getSpuDetail());//修改spu详细信息
        spuBo.getSkus().stream().filter(sku -> sku.getEnable()).forEach(sku -> {//循环sku
            sku.setSpuId(spuBo.getId());//关联spu

            TbStock tbStock = new TbStock();//创建sku写对象
            tbStock.setSkuId(sku.getId());//关联sku
            tbStock.setStock(sku.getStock());//存储sku的数量

            if(sku.getId()==null){//说明我们在修改的时候又新添加了一个sku
                sku.setCreateTime(new Date());//创建时间
                sku.setLastUpdateTime(sku.getCreateTime());//最后修改时间
                skuMapper.insertSelective(sku);//为null则添加
                tbStock.setSkuId(sku.getId());
                stockMapper.insertSelective(tbStock);//添加数量
            }else{//否则修改
                sku.setLastUpdateTime(new Date());//最后修改时间
                skuMapper.updateByPrimaryKeySelective(sku);//修改sku
                stockMapper.updateByPrimaryKeySelective(tbStock);//添加sku数量的数据
            }

        });
        //发送修改的消息
        sendMessage("update",spuBo.getId());
    }


    //回显spu详细信息
    public TbSpuDetail querySpuDetailById(Long id){
        return spuDetailMapper.selectByPrimaryKey(id);
    }

    //回显spu下的多个sku组成集合
    public List<TbSku> querySkusBySpuId(Long id) {
        TbSku tbSku = new TbSku();
        tbSku.setSpuId(id);
        return skuMapper.select(tbSku).stream().map(sku -> {
           sku.setStock(stockMapper.selectByPrimaryKey(sku.getId()).getStock());
           return sku;
        }).collect(Collectors.toList());
    }

    //删除---假删除，修改一下valid属性值
    public void deleteGoods(Long id){
        TbSpuBo tbSpuBo = new TbSpuBo();//创建spu对象
        tbSpuBo.setId(id);//关联spu
        tbSpuBo.setValid(false);//吧valid设置为false   false为删除  true为有效
        spuMapper.updateByPrimaryKeySelective(tbSpuBo);//修改表数据(假删除)
        //发送删除的消息
        sendMessage("delete",id);
    }

    //商品上下架
    public void saleableGoods(TbSpu spu) {
        spuMapper.updateByPrimaryKeySelective(spu);
        //发送上架下架修改的消息
        sendMessage("saleable",spu.getId());
    }

    //根据主键获取spu
    public TbSpu querySpuById(Long id) {
        return spuMapper.selectByPrimaryKey(id);
    }







/*
错的！！！
    //用于商品回显的
    public TbSpuBo querySpuById(Long id) {
        TbSpuBo tbSpuBo = new TbSpuBo();

        TbSpu tbSpu = spuMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(tbSpu,tbSpuBo);
        tbSpuBo.setSpuDetail(spuDetailMapper.selectByPrimaryKey(id));
        TbSku tbSku = new TbSku();
        tbSku.setSpuId(id);
        List<TbSku> select = skuMapper.select(tbSku);
        List<TbSku> collect = select.stream().map(sku -> {
            sku.setStock(stockMapper.selectByPrimaryKey(sku.getId()).getStock());
            return sku;
        }).collect(Collectors.toList());
        tbSpuBo.setSkus(collect);

        return tbSpuBo ;
    }*/
}
